<?php

namespace app\api\controller\coupons;
use app\common\controller\Api;
use think\Db;
use think\Config;
use app\api\controller\coupon\Basic;
use app\admin\model\coupons\Block;
use app\admin\model\coupons\Article;
use app\admin\model\coupons\Coupon;
use app\admin\model\coupons\Goods;

header('Access-Control-Allow-Origin:*');//允许跨域
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header('Access-Control-Allow-Headers:x-requested-with,content-type,token');
    //浏览器页面ajax跨域请求会请求2次，第一次会发送OPTIONS预请求,不进行处理，直接exit返回，但因为下次发送真正的请求头部有带token
    //所以这里设置允许下次请求头带token否者下次请求无法成功
    exit();
}

/**
 * 基本类，初始化请求
 * Class Base
 * @package app\api\controller\coupon
 */

class Common extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();
        $config = get_addon_config('coupons');
        $this->user_id = $this->auth->id=5;
    }


     /**
     * 获取首页海报+新闻
     *
     * 
     */
    public function index()
    {   
        //广告位列表
        $blockLists =Block::where('type','首页')->select();
        
        
    }

     /**
     * 获取小程序Token
     *
     * 
     */
    public function getAccessToken()
    {   
        $config = get_addon_config('coupons');
        //var_dump($config);exit;
        $appid=$config['wechat']['app_id'];
        $appsecret =$config['wechat']['app_secret'];
        $isExpires = $this->isExpires();

        if($isExpires === false){
            //到期，获取新的
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
            $res = $this->https_curl_json($url,'','json');
            // dump($res);
            $arr = json_decode($res,true);
            if($arr && !isset($arr['errcode'])){
                $arr['time'] = time();
                file_put_contents(APP_PATH . '/access_token.json', json_encode($arr));
                return $arr['access_token'];
            }else{
                echo 'error on get access_token';die;
            }
        }else{
            return $isExpires;
        }
        
    }

    
    
}
